<template>
    <div id="header">
        <hr size="2" color="#f6a606" style="margin: 0;width: 100%"/>
        <div style="height: 60px">
            <span class="title">ZhangLS's Blog</span>
            <div class="search">
                <input class="input" placeholder="请输入内容搜索" v-model="blog_search">
                <button class="button" @click="searchBlog"><i class="el-icon-search"></i></button>
            </div>
            <div class="mobile-menu-icon">
                <i class="el-icon-s-operation" @click="drawer=true"></i>
            </div>
            <!--PC端导航-->
            <div class="nav-PC">
                <el-menu class="el-menu-demo"
                         mode="horizontal"
                         text-color="#000"
                         active-text-color="#409EFF"
                         menu-trigger="click"
                         :default-active="$store.state.activeIndex"
                         @select="menuSelected">
                    <el-submenu index="1"  v-if="userInfo.avatar">
                        <template slot="title">
                                <el-avatar :size="40" class="avatar" :src="userInfo.avatar+'?n='+$store.state.timestamp"></el-avatar>
                                {{userInfo.nickname}}
                        </template>
                        <el-menu-item index="/userCenter" @click="userCenter"><i class="el-icon-user"></i>个人中心</el-menu-item>
                        <el-menu-item index="/logout" @click="logout"><i class="el-icon-back"></i>退出登录</el-menu-item>
                    </el-submenu>
                    <el-menu-item index="/index" @click="toIndex">首页</el-menu-item>
                    <el-menu-item index="/blog/edit" @click="$router.push('/blog/edit')">发表</el-menu-item>
                    <el-menu-item index="/statistics" @click="$router.push('/statistics')">统计</el-menu-item>
                    <el-menu-item index="/blog/1" @click="toAbout">关于</el-menu-item>
                    <el-menu-item index="/logout" v-if="userInfo.avatar" @click="logout">退出</el-menu-item>
                    <el-menu-item index="/login"  v-else @click="dialogVisible=true">登录</el-menu-item>
                </el-menu>
            </div>
            <!--移动端导航-->
            <div class="nav-mobile">
                <el-drawer title="我是标题" :visible.sync="drawer" :with-header="false" :modal="false" :size="300" direction="ltr">
                    <div style="display: inline-flex;margin: 20px 0 20px 20px">
                        <input class="input" placeholder="请输入内容搜索" v-model="blog_search">
                        <button class="button" @click="searchBlog"><i class="el-icon-search"></i></button>
                    </div>
                    <el-menu :default-active="$store.state.activeIndex"
                             class="el-menu-vertical-demo"
                             style="width: 300px;float: left;border: none"
                             @select="menuSelected_mobile">
                        <el-menu-item index="/userCenter" @click="userCenter" v-if="userInfo.avatar">
                            <el-avatar :size="40" class="avatar" :src="userInfo.avatar+'?n='+$store.state.timestamp"></el-avatar>
                            {{userInfo.nickname}}
                        </el-menu-item>
                        <el-menu-item index="/index" @click="toIndex"><i class="el-icon-s-home"></i>首页</el-menu-item>
                        <el-menu-item index="/blog/edit" @click="$router.push('/blog/edit')"><i class="el-icon-edit"></i>发表</el-menu-item>
                        <el-menu-item index="/statistics" @click="$router.push('/statistics')"><i class="el-icon-s-data"></i>统计</el-menu-item>
                        <el-menu-item index="/blog/1" @click="toAbout"><i class="el-icon-info"></i>关于</el-menu-item>
                        <el-menu-item index="/logout" v-if="userInfo.avatar" @click="logout"><i class="el-icon-back"></i>退出</el-menu-item>
                        <el-menu-item index="/login"  v-else @click="dialogVisible=true"><i class="el-icon-user-solid"></i>登录</el-menu-item>
                    </el-menu>
                </el-drawer>
            </div>
        </div>


        <!--登录对话框-->
        <el-dialog title="登录" :visible.sync="dialogVisible" :before-close="beforeClose" width="430px"
                   :modal-append-to-body="false" :close-on-click-modal="false" :modal="false"
                   @close="dialogClose('loginForm')" @open="dialogOpen">
            <el-form  :model="loginForm" :rules="rules" ref="loginForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="loginForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input  v-model="loginForm.password" show-password></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" id="login" @click="loginHandler('loginForm')">登录</el-button>
                    <el-button @click="register">注册</el-button>
                    <el-button @click="()=>{loginForm.username='guest';loginForm.password='123456'}">游客登录</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!--注册账号对话框-->
        <el-dialog title="注册" :visible.sync="dialogVisible_register" width="430px" :before-close="beforeClose"
                   :modal-append-to-body="false" :close-on-click-modal="false" :modal="false"
                   @close="dialogClose('registerForm')" @open="dialogOpen">
            <el-form :model="registerForm" :rules="rules" ref="registerForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerForm.username" maxlength="15" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input  v-model="registerForm.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                    <el-input  v-model="registerForm.checkPassword" show-password></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="registerForm.nickname" maxlength="8" show-word-limit></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="registerHandler" id="register">注册账号</el-button>
                    <el-button @click="goBackLogin">返回</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Header",
        data(){
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.registerForm.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                blog_search:'',
                drawer: false,   //抽屉是否打开
                userInfo:{
                    username:'',
                    nickname:'',
                    avatar:''
                },
                dialogVisible: false,           //登录对话框
                dialogVisible_register: false,  //注册对话框
                loginForm: {
                    username: '',
                    password: '',
                },
                registerForm: {
                    username: '',
                    password: '',
                    checkPassword:'',
                    nickname: '',
                },
                rules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                    ],
                    nickname: [
                        { required: true, message: '请输入昵称', trigger: 'blur' },
                    ],
                    checkPassword: [
                        { required: true, validator: validatePass, trigger: 'blur' },
                        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                    ]
                }
            }
        },
        watch: {
            '$store.state.needLogin': {
                handler(newVal, oldVal) {
                    if(newVal){
                        this.dialogVisible = true;
                        this.$message({type: "warning",message:this.$store.state.msg,showClose: true,duration:3000})
                        this.$store.commit('set_needLogin', {flag:false, msg:''})
                        this.$store.commit('reset_data')
                    }
                },
                immediate: true
            },
            '$store.state.userInfo': {
                handler(newVal, oldVal) {
                    this.userInfo = newVal;
                },
                deep:true
            },
            $route(to){
                if(to.path != '/index'){
                    this.blog_search = ''
                }
            }
        },
        methods: {
            getUserInfo(){
                this.$axios.post('/loginbytoken').then(res=>{
                    this.$store.commit('set_userInfo',res.data.data);
                })
            },
            logout(){
                if(!localStorage.getItem('token')){     //如果用户刪除token直接清除信息退出
                    this.$store.commit('reset_data');
                    return
                }
                this.$axios.post('/logout').then(res=>{
                    this.$store.commit('reset_data');
                    this.userInfo= {};
                })
            },
            toIndex(){
                if(this.$route.path == '/index'){
                    this.$router.push({path: "/blank",query:{to: '/index'}})
                    return
                }
                this.$router.push('/index')
                this.blog_search = ''
            },
            toAbout(){
                if(this.$route.name == 'BlogDetail'){
                    this.$router.push({path: "/blank",query:{to: '/blog/1'}})
                    return
                }
                this.$router.push('/blog/1')
            },
            searchBlog(){
                //新窗口打开
                this.drawer = false
                let routeData = this.$router.resolve({path:'/index',query:{search:this.blog_search}})
                window.open(routeData.href,'_blank')
            },
            menuSelected(index){    //菜单被选中时的回调
                this.$store.state.activeIndex = index
            },
            menuSelected_mobile(index){    //移动端菜单被选中时的回调
                this.$store.state.activeIndex = index
                if(index!='/login' && index != '/logout'){
                    this.drawer = false
                }
            },
            loginHandler(formName) {
                document.getElementById('login').blur()  //让按钮失焦，否则按下回车会自动执行按钮点击事件
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$axios.post("/login",this.loginForm).then(res=>{
                            const jwt = res.headers['authorization']
                            const userInfo = res.data.data;
                            this.$store.commit('set_token',jwt)
                            this.$store.commit('set_userInfo',userInfo)
                            this.userInfo= userInfo;
                            this.dialogVisible = false;
                            this.$store.state.activeIndex = this.$route.path    //激活菜单变回去
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            register(){
                this.$refs['loginForm'].resetFields()
                this.dialogVisible = false;
                this.dialogVisible_register = true;
            },
            goBackLogin(){  //从注册窗口返回登录窗口
                this.$refs['registerForm'].resetFields()
                this.dialogVisible_register = false;
                this.dialogVisible = true;
            },
            registerHandler(){  //注册账号
                document.getElementById('register').blur()  //让按钮失焦，否则按下回车会自动执行按钮点击事件
                this.$refs['registerForm'].validate((valid) => {
                    if (valid) {
                        this.$axios.post("/user/register",this.registerForm).then(res=>{
                            if(res.data.code == 200){
                                this.$message.success("账号注册成功");
                            }
                            this.dialogVisible_register = false;
                            this.$store.state.activeIndex = this.$route.path    //激活菜单变回去
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            beforeClose(done){  //登陆/注册对话框关闭前执行
                this.$store.state.activeIndex = this.$route.path    //激活菜单变回去
                done();
            },
            dialogOpen(){
                this.$store.state.activeIndex = '/login'
            },
            dialogClose(formName){  //每个对话框关闭后的回调，清空表单
                this.$refs[formName].resetFields()
            },
            userCenter(){   //转到用户中心界面
                this.$router.push('/userCenter')
            },
            handKeyCode(e) {  //用于监听键盘按下回车键进行登录
                let key = e.keyCode;
                if (key === 13) {
                    if(this.dialogVisible){
                        this.loginHandler('loginForm');
                    } else if(this.dialogVisible_register){
                        this.registerHandler();
                    } else if(this.blog_search!='' && document.activeElement.className=='input'){
                        this.searchBlog()
                    }
                    return false
                }
            }
        },
        created() {
            if(localStorage.getItem('token') && !this.$store.state.userInfo) {    //有token自动登录
                this.getUserInfo();
            }else if(this.$store.state.userInfo){
                this.userInfo = this.$store.state.userInfo;
            }
            //添加监听器，用于监听键盘按下回车键进行登录
            window.addEventListener('keydown',this.handKeyCode,true)

            if(this.$route.query.search){   //是否需要搜索
                this.blog_search = this.$route.query.search
            }
        }
    }
</script>

<style scoped>
    #header{
        color: #333;
        position: fixed;
        border-bottom: 2px solid #f1f2f5;
        background-color: rgba(255,255,255,1);
        width: 100%;
        Z-index: 2100;
        opacity: 0.95;
    }
    .title{
        font-size: 19px;
        font-weight: 300;
        margin-left: 12vw;
        line-height: 60px;
    }
    .search{
        margin-left: 13vw;
        display: inline-flex;
    }
    .nav-PC{
        display: inline-flex;
        position: absolute;
        right: 0;
    }
    .el-menu-item{
        text-align: center;
    }
    .nav-mobile{
        display: none;
    }
    @media (max-width: 1283px) { /*媒体宽度低于1283时*/
        .search{
            margin-left: 70px;
        }
        .title{
            margin-left: 70px;
        }
        .nav-mobile{
            display: none;
        }
    }
    @media (max-width: 1123px) { /*媒体宽度低于1123时*/
        .search{
            margin-left: 38px;
        }
        .title{
            margin-left: 23px;
        }
        .nav-mobile{
            display: none;
        }
    }
    .mobile-menu-icon{
        display: none;
    }
    @media (max-width: 1010px) { /*媒体宽度低于1010时*/
        .mobile-menu-icon{
            display: inline;
            position: absolute;
            right: 5vw;
            line-height: 60px;
            font-size: 24px;
        }
        .el-icon-s-operation:hover{
            color: orange;
            cursor: pointer;
        }
        .nav-PC{
            display: none;
        }
        .nav-mobile{
            display: block;
        }
        .search{
            display: none;
        }
        .title{
            margin-left: 30px;
        }
    }
    .el-menu{
        sborder-bottom: none;
        font-weight: 300;
        margin-right: 20px;
        display: inline-block;
        float: right;
    }
    .el-dropdown{
        position: relative;
        bottom: 3px;
    }
    .el-form{
        max-width: 400px;
        margin: 0 auto;
    }
    .el-icon-arrow-down {
        font-size: 11px;
    }
    .input{
        font-size: 14px;
        height: 34px;
        width: 150px;
        background: white;
        color: #222226;
        border: 2px solid #e8e8ed;
        outline-color: #31c2fc;
        border-radius: 19px 0 0 19px;
        padding: 0 20px;
    }
    .button{
        position: relative;
        width: 50px;
        height: 38px;
        border: 0 none;
        border-radius: 0 19px 19px 0;
        font-size: 16px;
        cursor: pointer;
        background-color: #31c2fc;
        color: white;
    }
    .button:hover{  /*鼠标覆盖时变色*/
        background-color: #0dadee;
    }
</style>
